package cn.gdust.dao;

import cn.gdust.entity.Barrage;
import cn.gdust.utils.DB;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class BarrageDao {
    public List<Barrage> findAll(String videoID) throws SQLException {
        List<Barrage> list = new ArrayList<>();
        String sql = "SELECT * FROM barrage WHERE video_id=?";
        Connection conn = DB.open();
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setString(1, videoID);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            Barrage barrage = new Barrage();
            barrage.setId(rs.getInt("id"));
            barrage.setVideo_id(rs.getInt("video_id"));
            barrage.setContent(rs.getString("content"));
            barrage.setColor(rs.getString("color"));
            barrage.setPosition(rs.getInt("position"));
            barrage.setCreatetime(rs.getDate("createtime"));
            list.add(barrage);
        }
        return list;
    }

    public int addBarrage(Barrage barrage) throws SQLException {
        String sql = "INSERT INTO barrage(video_id, content, position, color, createtime) VALUE(?, ?, ?, ?, now())";
        Connection conn = DB.open();
        PreparedStatement stmt = conn.prepareStatement(sql);
        stmt.setInt(1, barrage.getVideo_id());
        stmt.setString(2, barrage.getContent());
        stmt.setInt(3, barrage.getPosition());
        stmt.setString(4, barrage.getColor());
        // 返回改变的行数
        int count = stmt.executeUpdate();
        return count;
    }
}
